package com.dizang.ddd.business.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.CollectionUtils;

import com.dizang.ddd.dto.ProjectNodeDTO;
import com.dizang.ddd.entity.AbstractProjectBuilder;
import com.dizang.ddd.entity.ParentProject;
import com.dizang.ddd.entity.Project;

public abstract class AbstractCreateProjectBusiness {

	abstract protected List<String> buildPackage(ProjectNodeDTO node) ;

	public Project builEachProject(String path, ProjectNodeDTO parentNode, ProjectNodeDTO node) {
		String parentNodeName = parentNode != null ? parentNode.getName() : null;
		String nodeName = node != null ? node.getName() : null;
		List<ProjectNodeDTO> subList = node.getSubNode();
		
		if (!CollectionUtils.isEmpty(subList)) 
		for (ProjectNodeDTO subNode : subList) {

			String projectNameSub = subNode.getName();

			StringBuilder builder = new StringBuilder();
			builder.append(path);
			if (nodeName != null) {
				builder.append(nodeName);
			}
			builder.append("/");
			String nodePath = builder.toString();
			if ("java".equals(subNode.getSubType())) {
			    String groupId = subNode.getGroupId();
				List<String> buildPackage = buildPackage(subNode);
				List<AbstractProjectBuilder> dependencies = buildDependencies(subNode);
				Project common = new Project(projectNameSub,nodeName,groupId,dependencies,buildPackage);
				common.createProject(nodePath);
			} else {
				builEachProject(nodePath, node, subNode);
			}
		}
		
		List<AbstractProjectBuilder> dependencies = buildDependencies(node);
		List<AbstractProjectBuilder> buildModules = buildModules(node);
		Project nodeProject = new ParentProject(node.getName(),parentNodeName,node.getGroupId(),dependencies,null,buildModules);
		nodeProject.createProject(path);
		return nodeProject;

	}
	
    protected List<AbstractProjectBuilder> buildDependencies(ProjectNodeDTO node) {
        List<String> dependenciesNode = node.getDependencies();

        List<AbstractProjectBuilder> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(dependenciesNode))
        for (String projectNodeDTO : dependenciesNode) {
            Project projectCreator = new Project(projectNodeDTO,null,node.getGroupId(),null,null);
            list.add(projectCreator);
        }
        return list;
    }
    protected List<AbstractProjectBuilder> buildModules(ProjectNodeDTO node) {
        List<ProjectNodeDTO> subNode = node.getSubNode();
        if(CollectionUtils.isEmpty(subNode)) {
            return null;
        }
        List<AbstractProjectBuilder> list = new ArrayList<>();
        for (ProjectNodeDTO projectNodeDTO : subNode) {
            Project projectCreator = new Project(projectNodeDTO.getName(),null,null,null,null);
            list.add(projectCreator);
        }
        return list;
    }
}
